package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关的全局过滤器
 */
@Component
public class AuthorizerFilter implements GlobalFilter , Ordered {

    private static final String TOKEN = "Token";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //todo 1.拿到request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //todo 2.判断是否为登录请求,若是直接放行
        if (request.getPath().toString().contains("/api/v1/login/login_auth")) {
            return chain.filter(exchange);
        }
        //todo 3.拿到token 判断token是否为空和是否有效
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst(TOKEN);
        if (StringUtils.isEmpty(token) || AppJwtUtil.verifyToken(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
